/**
 * 预约系统相关模块方法
 */

// 当前设定日期
var day_stamp = "";
var modifydata = null;
var headOffset = 0;
var headCopy = null;

//页面载入初始化
$( "body" ).ready( function( e )
{
	init_invalid_td();
	day_stamp=$("#datetime").val();
	try
	{
		if( typeof ( eval( "init" ) ) == "function" )
			eval( "init();" );
	}
	catch( e )
	{
	}
	
	// 区域选择
	$( "#region" ).change( region_changed );
	//update_office_info();

	// 数据事件
	parent.dispatcher.unbind( "reserve_new", reserveHandler );
	parent.dispatcher.unbind( "reserve_update", reserveHandler );
	parent.dispatcher.bind( "reserve_new", reserveHandler );// 增加预约
	parent.dispatcher.bind( "reserve_update", reserveHandler );// 更新预约

	// 初始化
	select_date( 'datetime', dateSelected );
	init_th_head();
	init_invalid_td();
	//init_week_data();
	init_td_hover();
	ttt = true;
} );

function reserveHandler( e, data )
{
	var datetime = $("#datetime").val();
	var region = $("#region").val();
	window.location.href=encodeURI(contextPath+"/index/consultant_client_reserve.htm?datetime="+datetime+"&region="+region);
}

function region_changed( e )
{
	var datetime = $("#datetime").val();
	var region = $("#region").val();
	location.href = url_param( location.href, { region: region,datetime:datetime } );
}

/*function init_week_data()
{
	var size = modifydata.length;

	for( var i = 0; i < size; i++ )
	{
		var d = modifydata[ i ];
		var date = d.date;
		var time = d.time;
		var td = gettd_bydatetime( date, time );

		if( td.text() == "closed" )
			td.text( "" );
		fill_reserve( td, d );
		//fill_holdtime( td, d );
	}
}*/

function init_invalid_td()
{
	$( "#reservelst tr td[rel='rest']" ).each( function()
	{
		close_td( $( this ) );
	} );
}

function close_td( tar, txt )
{
	if( typeof ( txt ) == "undefined" ){
		txt = "colsed";
	}
	tar.attr( "rel", "rest" );
	tar.css( { "background": "#eee url("+path+"/img/td_bg.png)", "text-align": "center", "color": "#e6e6e6" } );
	tar.text( txt );
}

function init_th_head()
{
	headOffset = $( "#weekrow" ).offset();
	
	var tbl = $( "#reservelst" ).clone();
	tbl.find( "tr:not(:first)" ).remove();
	tbl.css( { "border-collapse": "collapse" } );
	tbl.find( "th" ).css( { "border": "1px solid #f0f0f0" } );

	$( "body" ).append( tbl );
	$( "body" ).append( "<div id='__HEAD_COPY'></div>" );

	headCopy = $( "#__HEAD_COPY" );
	tbl.appendTo( headCopy );
	headCopy.css( { "position": "absolute", "background-color": "#fcfcfc" } );

	$( window ).scroll( function()
	{
		if( $( this ).scrollTop() >= headOffset.top )
		{
			headCopy.show();
			headCopy.offset( { top: $( this ).scrollTop(), left: headOffset.left } );
			headCopy.find( "table" ).width( $( "#reservelst" ).width() );
		}
		else
		{
			headCopy.hide();
		}
	} );
}

function init_td_hover()
{
	// 单元格样式处理
	$( "#reservelst" ).find( "td[rel!='rest']" ).each(
			function( id )
			{
				if( empty( $( this ).attr( "rel" ) ) )
				{
					$( this ).hover(
							function()
							{
								$( this ).parent().css( "background-color", "#D8A5CC" );
								$( this ).css( "background-color", "#edf" );

								var ts = $( this ).parent().find( ":first" ).add(
										$( "#reservelst tr:first th" ).eq( $( this ).index() ) );
								$( "#__HEAD_COPY table tr th" ).eq( $( this ).index() ).css(
										{ "background-color": "#D8A5CC", "color": "#fff" } );
								ts.css( { "background-color": "#D8A5CC", "color": "#fff" } );
							},
							function()
							{
								$( this ).parent().css( "background-color", "" );
								$( this ).css( "background-color", "" );

								var ts = $( this ).parent().find( ":first" ).add(
										$( "#reservelst tr:first th" ).eq( $( this ).index() ) );
								$( "#__HEAD_COPY table tr th" ).eq( $( this ).index() ).css(
										{ "background-color": "", "color": "" } );
								ts.css( { "background-color": "", "color": "" } );
							} );

					// 单元格事件绑定
					$( this ).click( tdClickHandler );
				}
			} );

	// 表格行背景
	setTableRowBackColor( $( "#reservelst" ) );

}

//为表格行添加交替背景色
function setTableRowBackColor( table )
{
	var trs = table.find( "tr:visible[class!=fields]" );

	trs.each( function( id )
	{
		$( this ).attr( "class", id % 2 == 0 ? "even_row" : "odd_row" );
	} );
}

function tdClickHandler( e )
{
	event.stopPropagation();
	var idx = $( this ).index();
	var time = $( this ).parent().find( "th" ).text();
	var week = $( "#reservelst tr:first th" ).eq( idx ).html();
	var date = week.split( "<br>" )[ 0 ];
	var region = $( "#region" ).val();

	var id = parent.create_model(contextPath+"/index/consultant_client_reserve_form.htm?time="+time+"&date="+date+"&region="+region, "编辑预约信息", null, 8000 );
	parent.mask_layer.index( 7999 );
	parent.open_model( id ,true);
}


/*function tdClickHandler( e )
{
	e.stopPropagation();

	var idx = $( this ).parent().index();
	var time = $( this ).parent().find( "th" ).text();
	var date = $( "#reservelst tr:first th" ).eq( idx ).find("span").first().html();
	var region = $( "#region" ).val();
	var keyname = $(this).find("div").attr("id");
	
	var thiss = $( this ).html();
	if(thiss.length>100){
		window.open(contextPath+"/index/consultant_client_reserve_form.htm?time="+time+"&date="+date+"&keyname="+keyname);
	}else{
		$.post(contextPath+"/index/selectdate.json", {
			"date":date,
			"time":time
		}, function(ms) {
			var msg = ms.msg;
			if(msg=="0"){
				alert("时间过期");
			}else{
				window.open(contextPath+"/index/consultant_client_reserve_form.htm?time="+time+"&date="+date+"&keyname="+keyname);
			}
		});
	}
	
}*/

function tdViewHandler( e )
{
	e.stopPropagation();
	
	var idx = $(this).parent().index();
	var time = $( this ).parent().parent().find( "th" ).text();
	var week = $( "#reservelst tr:first th" ).eq( idx ).html();
	var date = week.split( "<br>" )[ 0 ];
	var region = $( "#region" ).val();
	var keyname = $(this).attr("id");
	var id = parent.create_model(contextPath+"/index/consultant_client_reserve_form.htm?time="+time+"&date="+date
			+ "&keyname="+keyname, "编辑预约信息", null, 8000 );
	parent.mask_layer.index( 7999 );
	parent.open_model( id ,true);
	
	
}

/**
 * 根据指定的类型设置当前表单所显示的时间范围
 * 
 * @param flag
 *            <ul>
 *            <li>-1：上一周</li>
 *            <li>0：本周</li>
 *            <li>1：下一周</li>
 *            </ul>
 */
function cdatetime( flag )
{	
	var ds = day_stamp.split( "-" );
	var d = new Date();
	d.setFullYear( parseInt( ds[ 0 ] ), parseInt( ds[ 1 ] ) - 1, parseInt( ds[ 2 ] ) );
	
	var week = d.getDay();
	var ms = d.getTime();
	var kd = 0;

	week = week == 0 ? 7 : week;

	if( flag == -1 )
	{
		kd = week * -1;
		d.setTime( ms + kd * 86400000 );
	}
	else if( flag == 1 )
	{
		kd = 8 - week;
		d.setTime( ms + kd * 86400000 );
	}
	else if( flag == 2 )
	{
		window.location.reload();
		return;
	}
	else
	{
		kd = 0;
		d = new Date();
	}
	var datetime = (d.getFullYear() + "-" + ( d.getMonth() + 1 ) + "-" + d.getDate());
	var region = $("#region").val();
	location.href = "?datetime=" + datetime+"&region="+region;
}

function url_param( u, p )
{
	var up = param( u );
	var url = u.replace( /(.*?)\?(.*?)/, "$2" );
	url = u.replace( "?" + url, "" );
	if( typeof ( p ) == "object" )
	{
		for( var attr in p )
		{
			up[ attr ] = p[ attr ];
		}
	}

	var ps = [];

	for( var attr in up )
	{
		ps.push( attr + "=" + up[ attr ] );
	}
	return url + "?" + ps.join( "&" );
}

function dateSelected( val, date )
{
	var datetime = $("#datetime").val();
	var region = $("#region").val();
	location.href = "?datetime=" + datetime+"&region="+region;
}

//--------------------------------------------------------------------------
//
//	页面初始化时填充预约数据
//
//--------------------------------------------------------------------------

function gettd_bydatetime( date, time )
{
	var $tbl = $( "#reservelst" );
	var dateIdx = 0;
	var td = null;

	$tbl.find( "tr:first th" ).each( function( id )
	{
		// 第一格是左上角空位
		if( id > 0 )
		{
			if( $( this ).text().indexOf( date ) != -1 )
			{
				dateIdx = id;
				return false;
			}
		}
	} );

	$tbl.find( "tr:not(:first)" ).each( function( id )
	{
		if( $( this ).find( "th" ).text().indexOf( time ) != -1 )
		{
			td = $( this ).find( "td" ).eq( dateIdx - 1 );
			return false;
		}
	} );

	return td;
}

function fill_reserve( target, data )
{
	var bkColor = "#ccc";
	var fontColor = "#fff";
	var lineColor = "#eee";

	switch( parseInt( data.state ) ) {
		case 1:
		{
			bkColor = "#D5B1F8";
			fontColor = "#ffffff";
			lineColor = "#eee";
			break;
		}
		case 2:
		{
			bkColor = "#E7F8B1";
			fontColor = "#333333";
			lineColor = "#ccc";
			break;
		}
		case 3:
		{
			bkColor = "#cccccc";
			fontColor = "#EDEDED";
			lineColor = "#eee";
			break;
		}
	}

	// 单个预约信息块
	// 去除单元格内容，因为有可能是已经过期的时间被 close掉了
	var id = data.key;
	target.append( "<div id='" + id + "'></div>" );

	var tar = target.find( "#" + id );
	var cssdata = { "background-color": bkColor, "background-repeat": "no-repeat", "line-height": "20px",
		"background-position": "96% 2px", "text-align": "center", "color": fontColor, "cursor": "pointer" };

	if( data.sms == "1" )
	{
		cssdata[ "background-image" ] = "url(img/sms.png)";
	}
	else
	{
		cssdata[ "background-image" ] = "url(img/sms-gray.png)";
	}

	var ht = data.nickname + "<br>";

	if( data.non == "1" )
	{
		// 非测评预约
		ht += data.notice;
	}
	else
	{
		// 测评预约，显示学员列表
		var sns = data.studentns.split( "," );
		for( var i = 0; i < sns.length; i++ )
		{
			ht += sns[ i ] + "<br>";
		}
	}
	ht += "<p style='color:" + lineColor + ";font-size:12px;border-top:1px dotted " + lineColor + ";'>"
			+ data.cdate + "</p>";
	tar.html( ht );

	tar.addClass( "unit" );
	tar.css( cssdata );
	tar.attr( "rel", data.key );
	tar.attr( "title", "[ " + data.time + " ] " + data.nickname + " | " + data.sourcens + " | "
			+ data.categoryns + "\n( 发起人：" + data.sponsor + " )" );
	tar.click( tdViewHandler );
}

/**
 * 根据当前预约点，以及持续时间来体现占据时间段
 * 
 * @param tar
 * @param time
 */
function fill_holdtime( tar, data )
{
	var times = data.needtime / 0.5;
	var idx = tar.parent().index();
	var trs = $( "#reservelst tr" );
	var td = null;

	for( var i = 1; i < times; i++ )
	{
		td = trs.eq( idx + i ).find( "td" ).eq( tar.index() - 1 );
		if( typeof ( td.attr( "rel" ) ) == "undefined" && data.state == 1 )
		{
			td.attr( "title", "被占据，不可使用" );
			close_td( td, "hold" );
		}
	}
}

//--------------------------------------------------------------------------
//
//	当切换中心地址时，更新当前中心的资料信息
//
//--------------------------------------------------------------------------
//
//var WEEKS = [ "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" ];
//
//function update_office_info()
//{
//	var region = $( "#region" ).val();
//
//	submitter.post( contextPath+"/index/consultant_office_get.json", { region: region }, function( d )
//	{
//		if( d.err == 0 )
//		{
//			var days = empty( d.restday ) ? [] : d.restday.split( "," );
//			var info = "";
//			info += "<label><b>中心地址：</b><span class='unit'>" + d.address + "</span></label>";
//			info += "<label><b>联系电话：</b><span class='unit'>" + d.inphone + "</span></label>";
//			info += "<label><b>休息日：</b>";
//			for( var i = 0; i < days.length; i++ )
//			{
//				info += "<span class='unit'>" + WEEKS[ days[ i ] - 1 ] + "</span>";
//			}
//			if( days.length == 0 )
//				info += "<span class='unit'>未设置</span>";
//			info += "</label>";
//
//			$( "#office_info" ).html( info );
//			$( "#office_notice > div" ).html( d.notice );
//			
//			// 重新定位预约表头位置
//			headOffset = $( "#weekrow" ).offset();
//		}
//		else
//		{
//			//infopad.err( d.msg );
//		}
//	}, "json" );
//}

//--------------------------------------------------------------------------
//
//	methods
//
//--------------------------------------------------------------------------
//数据填充
/*var getFollow = function(){
	var region = $("#region").val();
	var date = $("#dates").val();
	$.post(contextPath+"/index/get_client_reserve.json", {
		"region":region,
		"date":date
	}, function(ms) {
		var list = ms.list;
		for(var j=0;j<list.length;j++){
			var re = new RegExp("-", "g");
			var ids = (list[j].dates).replace(re,"")+(list[j].time).replace(":","");
			var htm = $("#"+ids).html(" ");
		}
		
		for(var i=0;i<list.length;i++){
			var objHtml = ""
			var re = new RegExp("-", "g");
			var ids = (list[i].dates).replace(re,"")+(list[i].time).replace(":","");
			var keyname = "";
			var stuNickname = "";
			var keyname = "";
			var id = "";
			for(var k=0;k<list[i].students.length;k++){
				if(list[i].students[0].nickname==undefined){
					stuNickname = "";
				}else{
					stuNickname = list[i].students[0].nickname;
				}
			}
			keyname = list[i].client;
			if(list[i].state=="1"){
				var classs="line-height: 20px; text-align: center; color: rgb(255, 255, 255); cursor: pointer; background-image: url(&quot;${staticServer}/img/sms.png&quot;); background-color: rgb(213, 177, 248); background-position: 96% 2px; background-repeat: no-repeat;"
				var class1 = 'color:#eee;font-size:12px;border-top:1px dotted #eee;';
			}else if(list[i].state=="2"){
				var classs='line-height: 20px; text-align: center; color: rgb(51, 51, 51); cursor: pointer; background-image: url(&quot;${staticServer}/img/sms.png&quot;); background-color: rgb(231, 248, 177); background-position: 96% 2px; background-repeat: no-repeat;';
				var class1 = 'color:#ccc;font-size:12px;border-top:1px dotted #ccc;';
			}else if(list[i].state=="3"){
				var classs='line-height: 20px; text-align: center; color: rgb(237, 237, 237); cursor: pointer; background-image: url(&quot;${staticServer}/img/sms.png&quot;); background-color: rgb(204, 204, 204); background-position: 96% 2px; background-repeat: no-repeat;';
				var class1 = 'color:#eee;font-size:12px;border-top:1px dotted #eee;';
			}
			id = list[i].client;
			objHtml ='<div id="'+list[i].client+'" class="unit"  rel="'+list[i].dates+'" title="[ '+list[i].time+' ] '+list[i].nickname+' | '+list[i].sourcens+' | '+list[i].categoryns+'( 发起人：'+list[i].sponsor+' )" style="'+classs+'">'+list[i].nickname+'<br>'+stuNickname+'，男，10岁<br><p style="'+class1+'">'+list[i].dates+' '+list[i].time+'</p></div>'
			$("#"+ids).append(objHtml);
			var tar = $("#"+keyname);
			tar.click( tdViewHandler );
		}
	});
}*/

function select_date( targetid, func )
{
	$( '#' + targetid ).Zebra_DatePicker( { format: 'Y-m-d', show_icon: false, onSelect: func } );
}
